<?php

namespace app\admin\controller\cooperate;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\constant;
/**
 * 考核
 *
 * @icon fa fa-circle-o
 */
class Track extends Backend
{
    /**
     * Apply模型对象
     * @var
     */
    protected $track = null;
    protected $number = null;
    protected $instance = null;
    protected $task = null;
    protected $scheme = null;
    protected $flow = null;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = '';

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->track = new \app\admin\model\flow\Track();
        $this->number = new \app\admin\model\flow\Number();
        $this->instance = new \app\admin\model\flow\Instance();
        $this->task = new \app\admin\model\flow\Task();
        $this->scheme = new \app\admin\model\flow\Scheme();
    }

    /**
     * 导入
     */
    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //设置自己账号只能查看自己的
            $unitWhere = [];
            $uInfo = $this->auth->getUserInfo();
            if(!empty($uInfo['id']) && isset($uInfo['id'])){
                $unitWhere['originator'] = ['in', $uInfo['id']];
            }

            //如果是管理员账号可以查看所有的
            if(in_array($uInfo['id'],constant\Consts::$Super)
                or $uInfo['nickname']=='王姝'
                or $uInfo['nickname']=='刘霆' or $uInfo['nickname']=='张大松') {
                $unitWhere = [];
            }

            /*$total = Db::name('view_flow_workitem')
                ->where($where)
                ->where($unitWhere)
                ->where(['schemeid' => 2])
                ->where('deletetime','null')
                ->order($sort, $order)
                ->order('createtime desc,status asc,completedtime desc')
                ->count();

            $list = Db::name('view_flow_workitem')
                ->where($where)
                ->where($unitWhere)
                ->where(['schemeid' => 2])
                ->where('deletetime','null')
                ->order('createtime desc,status asc,completedtime desc')
                ->limit($offset, $limit)
                ->select();*/

//            $total = Db::name('my_flow_workitem')
//                ->where($where)
//                ->where($unitWhere)
//                ->where(['schemeid' => 2])
//                //->where('deletetime','null')
//                //->order($sort, $order)
//                ->order('createtime desc,status asc,completedtime desc')
//                ->count();
//
//            $list = Db::name('my_flow_workitem')
//                ->where($where)
//                ->where($unitWhere)
//                ->where(['schemeid' => 2])
//                //->where('deletetime','null')
//                ->order('createtime desc,status asc,completedtime desc')
//                ->limit($offset, $limit)
//                ->select();

            $total = Db::name('flow_instance')
                ->where($where)
                ->where($unitWhere)
                ->where(['scheme' => 2])
                //->order($sort, $order)
                ->order('instancecode desc,createtime desc')
                ->count();

            $list = Db::name('flow_instance')
                ->alias('instance')
                ->join('admin admin', 'admin.id = instance.originator')
                ->field('instance.*, admin.department_id')
                ->where($where)
                ->where($unitWhere)
                ->where(['scheme' => 2])
                ->order('instancecode desc,createtime desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach($list as &$item){
                //增加发起人
                $item['initiator_id'] = Db::name('admin')->where(['id' => $item['originator']])->value('nickname');;

                if($item['bizobjectid']){
                    $track = Db::name('flow_track')->where(['id' => $item['bizobjectid']])->find();
                    if(!empty($track)){
                        $item['cname'] = Db::name('flow_cooperation')->where('id' , $track['partner_id'])->value('cname');
                        $item['year'] = isset($track['year'])?$track['year']:'';
                    }
                }
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $adminList = Db::name('admin')->field('id,nickname')->select();
        $this->assignConfig('adminList', array_column($adminList, 'nickname', 'id'));
        $deptList = Db::name('department')->field('id,name')->select();
        $this->assignConfig('deptList', array_column($deptList, 'name', 'id'));

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $ids = $this->request->request('ids');
        $bizobjectid =Db::name('view_flow_instance')->where(['scheme' => 2])->where(['id' => $ids])->value('bizobjectid');
        $row = Db::name('flow_track')->where(['id' => $bizobjectid])->find();
        if(!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                //var_dump($params);exit;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //$result = $row->allowField(true)->save($params);
                    $result = Db::name('flow_track')->where(['id' => $bizobjectid])->update($params);
                    Db::commit();
                }
                catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                }
                else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $delIds = [];
            $delIds = explode(',', $ids);
            $delIds = array_unique($delIds);
            $bizobjectids = Db::name('view_flow_instance')->where(['scheme' => 2])->where('id', 'in', $delIds)->column('bizobjectid');
            $bizobjectIds = array_unique($bizobjectids);
            $this->instance->where(['scheme' => 2])->where('id', 'in', $delIds)->delete();
            $this->task->where('instanceid', 'in', $delIds)->delete();
            $count = $this->track->where('id', 'in', $bizobjectIds)->delete();
            if ($count) {
                $this->success();
            }
        }
    }
}
